#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <unistd.h>
#include <errno.h>
#include "gpio.h"


gpio::gpio(int num)
{
    /* init buffer */
    snprintf(mbuffer_num, BUFS_NUM, "%d", num);
    snprintf(mbuffer_diretion, BUFS_DIRETION, "/sys/class/gpio/gpio%d/direction", num);
    snprintf(mbuffer_value, BUFS_VALUE, "/sys/class/gpio/gpio%d/value", num);
}

gpio::~gpio()
{

}

int gpio::opendev()
{
    /* export */
    mfd = open("/sys/class/gpio/export", O_WRONLY);
    if (-1 == mfd) {
        perror("open /sys/class/gpio/export");
        return -1;
    }
    if (access(mbuffer_value, 00) == -1) {
        if (write(mfd, mbuffer_num, (int)strlen(mbuffer_num)) != (int)strlen(mbuffer_num)) {
            perror("write export");
            return -1;
        }
    }
    close(mfd);
    /* get value handle */
    mfd_value = open(mbuffer_value, O_WRONLY);
    if (-1 == mfd_value) {
        perror("open /sys/class/gpio/gpioX/value");
        return -1;
    }
    return 0;
}

int gpio::closedev()
{
    /* unexport */
    mfd = open("/sys/class/gpio/unexport", O_WRONLY);
    if (-1 == mfd) {
        perror("open /sys/class/gpio/unexport");
        return -1;
    }
    if (write(mfd, mbuffer_num, (int)strlen(mbuffer_num)) != (int)strlen(mbuffer_num)) {
        perror("write export");
        return -1;
    }
    close(mfd);
    return 0;
}

int gpio::get_value()
{
   lseek(mfd_value, 0, SEEK_SET);
   if (read(mfd_value, mbuffer_tmp, 1) != 1) {
       perror("read");
       return -1;
   }
   mbuffer_tmp[1] = '\0';
   return atoi(mbuffer_tmp);
}

int gpio::set_diretion(int diretion)
{
    mfd = open(mbuffer_diretion, O_WRONLY);
    if (-1 == mfd) {
        perror("open direction");
        return -1;
    }
    if (0 == diretion) {
        if (write(mfd, "out", 3) != 3) {
            perror("write direction");
            return -1;
        }
    } else {
        if (write(mfd, "in", 2) != 2) {
            perror("write direction");
            return -1;
        }
    }
    close(mfd);
    return 0;
}

int gpio::set_value(int value)
{
    mfd = open(mbuffer_value, O_WRONLY);
    if (-1 == mfd) {
        perror("open value");
        return -1;
    }
    if (0 == value) {
        if (write(mfd, "0", 1) != 1) {
            perror("write value");
            return -1;
        }
    } else {
        if (write(mfd, "1", 1) != 1) {
            perror("write value");
            return -1;
        }
    }
    close(mfd);
    return 0;
}















